package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.exception.NoGoods;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SecKillService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckillController")
public class SecKillController {

    @Reference
    private SecKillService secKillService;

    //跳转秒杀首页
    @RequestMapping("toSeckillIndex")
    public String toSeckillIndex(Model model){
        //获取秒杀商品列表
        List<TbSeckillGoods> seckillGoodsList = secKillService.getGoodList();
        model.addAttribute("seckillGoods", seckillGoodsList);
        return "seckill-index";
    }

    //根据Id获取秒杀商品详情
    @RequestMapping("findSeckillById/{id}")
    public String findSeckillById(@PathVariable("id")Long id, Model model){
        TbSeckillGoods seckillGood = secKillService.findSeckillById(id);
        model.addAttribute("seckillGood", seckillGood);
        return "seckill-item";
    }

    //生成订单
    @RequestMapping("createOrder/{id}")
    @ResponseBody
    private Result createOrder(@PathVariable("id")Long id){
        //判断用户是否登录
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if(user == null){
            return Result.build(ConstantEnum.NO_AUTH);
        }
        try {
            secKillService.createOrder(id, user.getUsername());
        } catch (NoGoods e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("秒杀失败, 商品售罄或您已抢购过该商品");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.build(ConstantEnum.SUCCESS);
    }
}
